package com.winning.ds.common.util;

import com.winning.ds.common.entity.TreeEntity;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;


/**
 * 递归构造树型结构
 */
public class TreeUtil {

    private List<TreeEntity> treeList = new ArrayList<>();

    /**
     * 建立树形结构
     * @param jgList  机构集合
     * @param rotNode  根节点编码
     * @return
     */
    public List<TreeEntity> builTree(List<TreeEntity> jgList, String rotNode) {
        this.treeList = jgList;
        List<TreeEntity> treeResults = new ArrayList<>();
        for (TreeEntity JgTreeNode : getRootNode(rotNode)) {
            JgTreeNode = buildChilTree(JgTreeNode);
            treeResults.add(JgTreeNode);
        }
        return treeResults;
    }

    /**
     * 建立树形结构
     * @param treeList  所有集合
     * @param rootList  根集合
     * @return
     */
    public List<TreeEntity> builTree(List<TreeEntity> treeList, List<TreeEntity> rootList) {
        this.treeList = treeList;
        List<TreeEntity> treeResults = new ArrayList<>();
        for (TreeEntity treeNode : rootList) {
            treeNode = buildChilTree(treeNode);
            treeResults.add(treeNode);
        }
        return treeResults;
    }


    /**
     * 递归，建立子树形结构
     * @param pNode 上级节点实体
     * @return
     */
    private TreeEntity buildChilTree(TreeEntity pNode) {
        List<TreeEntity> chilJgTrees = new ArrayList<>();
        for (TreeEntity jgTreeNode : treeList) {
            if (StringUtils.trimToEmpty(jgTreeNode.getPId()).equals(pNode.getId())) {
                chilJgTrees.add(buildChilTree(jgTreeNode));
            }
        }
        if (CollectionUtils.isNotEmpty(chilJgTrees)) {
            pNode.setChildren(chilJgTrees);
        }
        return pNode;
    }

    /**
     * 获取根节点
     * @param jgbm 跟节点编码
     * @return
     */
    private List<TreeEntity> getRootNode(String jgbm) {
        List<TreeEntity> rootJgTrees = new ArrayList<>();
        for (TreeEntity jgTreeNode : treeList) {
            if (jgbm.equals(jgTreeNode.getPId())) {
                rootJgTrees.add(jgTreeNode);
            }
        }
        return rootJgTrees;
    }

}









